package com.huitong.auth.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.huitong.auth.domain.vo.CaptchaVO;
import com.huitong.auth.enums.CaptchaType;
import com.huitong.auth.properties.CaptchaProperties;
import com.huitong.common.core.domain.Result;
import com.huitong.common.redis.constant.CacheConstant;
import com.huitong.common.redis.utils.RedisUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.UUID;

/**
 * 验证码控制层
 *
 * @author fromdrowning
 * @date 2024/3/20 23:19
 */
@RequiredArgsConstructor
@RestController
public class CaptchaController {

    /**
     * 验证码配置
     */
    private final CaptchaProperties captchaProperties;

    /**
     * 获取验证码
     *
     * @return 验证码
     */
    @SaIgnore
    @GetMapping("/captcha")
    public Result<CaptchaVO> getCode() {
        // 生成验证码
        CaptchaType captchaType = captchaProperties.getType();
        boolean isMath = CaptchaType.MATH == captchaType;
        int length = isMath ? captchaProperties.getNumberLength() : captchaProperties.getCharLength();
        CodeGenerator codeGenerator = ReflectUtil.newInstance(captchaType.getClazz(), length);
        AbstractCaptcha captcha = SpringUtil.getBean(captchaProperties.getCategory().getClazz());
        captcha.setGenerator(codeGenerator);
        captcha.createCode();

        String code = captcha.getCode();
        if (isMath) {
            // 数字验证码需要计算正确结果
            ExpressionParser parser = new SpelExpressionParser();
            code = parser.parseExpression(StrUtil.replace(code, "=", StrUtil.EMPTY))
                .getValue(String.class);
        }

        // 保存验证码信息
        String uuid = UUID.randomUUID().toString();
        String verifyKey = CacheConstant.CAPTCHA_KEY_NAME + uuid;
        RedisUtils.setCacheObject(verifyKey, code, Duration.ofMinutes(CacheConstant.CAPTCHA_EXPIRATION));

        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setUuid(uuid);
        captchaVO.setImage(captcha.getImageBase64());

        return Result.success(captchaVO);
    }
}
